<template>
  <a-upload-dragger
    name="file"
    :multiple="true"
    :data="formKeyData"
    :action="uploadParams.actionUrl"
    :headers="uploadParams.headers"
    :accept="accept"
    :fileList="fileList"
    :disabled="disabled"
    :remove="handleRemove"
    :beforeUpload="beforeUpload"
    @change="handleChange"
  >
    <p class="ant-upload-drag-icon">
      <a-icon type="inbox" />
    </p>
    <p class="ant-upload-text">
      点击并拖拽到此区域上传
    </p>
    <p class="ant-upload-hint">
      支持单次或批量上传
    </p>
  </a-upload-dragger>
</template>
<script>
export default {
  props: {
    uploadParams: {
      type: Object,
      default: null,
      required: false
    },
    fileSize: {
      type: Number,
      required: false,
      default: 2
    },
    accept: {
      type: String,
      required: false,
      default: 'image/*'
    },
    // 新增number属性，用于判断上传数量
    number: {
      type: Number,
      required: false,
      default: 0
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      previewImage: '',
      previewVisible: false,
      token: '',
      formKeyData: {
        token: '',
        key: ''
      },
      uploadHost: this.uploadParams.uploadHost
    }
  },
  methods: {
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < this.fileSize

      return new Promise((resolve, reject) => {
        if (this.accept == 'image/*') {
          if (!isJpgOrPng) {
            this.$message.error('上传格式有误！')
            reject(file)
          }
        }
        if (!isLt2M) {
          this.$message.error(`图片请小于${this.fileSize}MB!`)
          reject(file)
        } else {
          const key = new Date().getTime() + '-' + file.name
          this.formKeyData = {
            key: key,
            token: this.token
          }
          // return isJpgOrPng && isLt2M
          resolve(file)
        }
      })
    },
    handleChange(info) {
      if (fileList.length > this.number && this.isMultiple) {
        this.$message.warning('最多上传' + this.number + '张！')
        return false
        // fileList = fileList.slice(-this.number)
      }
      const status = info.file.status
      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully.`)
      } else if (status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    }
  }
}
</script>
